// API服务配置和封装
// 在开发环境使用代理，生产环境使用相对路径
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || (
  import.meta.env.DEV ? 'http://localhost:5000/api/v1' : '/api/v1'
);

class ApiService {
  constructor() {
    this.baseURL = API_BASE_URL;
  }

  async request(endpoint, options = {}) {
    const url = `${this.baseURL}${endpoint}`;
    const config = {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers,
      },
      ...options,
    };

    try {
      const response = await fetch(url, config);
      const data = await response.json();
      
      if (!response.ok) {
        throw new Error(data.message || '请求失败');
      }
      
      return data;
    } catch (error) {
      console.error('API请求错误:', error);
      throw error;
    }
  }

  // 通用HTTP方法
  async get(endpoint, options = {}) {
    return this.request(endpoint, {
      method: 'GET',
      ...options,
    });
  }

  async post(endpoint, data = {}, options = {}) {
    return this.request(endpoint, {
      method: 'POST',
      body: JSON.stringify(data),
      ...options,
    });
  }

  async put(endpoint, data = {}, options = {}) {
    return this.request(endpoint, {
      method: 'PUT',
      body: JSON.stringify(data),
      ...options,
    });
  }

  async delete(endpoint, options = {}) {
    return this.request(endpoint, {
      method: 'DELETE',
      ...options,
    });
  }

  // 健康检查
  async healthCheck() {
    return this.request('/health');
  }

  // 数据管理相关API
  async importData(file) {
    const formData = new FormData();
    formData.append('file', file);
    
    return this.request('/data/historical/import', {
      method: 'POST',
      body: formData,
      headers: {}, // 移除Content-Type让浏览器自动设置
    });
  }

  async getHistoricalData(params = {}) {
    const queryString = new URLSearchParams(params).toString();
    return this.request(`/data/historical/query?${queryString}`);
  }

  async getBusinessUnits() {
    return this.request('/data/historical/business-units');
  }

  async getMetrics() {
    return this.request('/data/historical/metrics');
  }

  async getDataStatistics() {
    return this.request('/data/historical/statistics');
  }

  // 预测分析相关API
  async createPredictionTask(taskData) {
    return this.request('/prediction/tasks', {
      method: 'POST',
      body: JSON.stringify(taskData),
    });
  }

  async getPredictionTasks(params = {}) {
    const queryString = new URLSearchParams(params).toString();
    return this.request(`/prediction/tasks?${queryString}`);
  }

  async getTaskStatus(taskId) {
    return this.request(`/prediction/tasks/${taskId}/status`);
  }

  async getTaskResults(taskId) {
    return this.request(`/prediction/tasks/${taskId}/results`);
  }

  async deleteTask(taskId) {
    return this.request(`/prediction/tasks/${taskId}`, {
      method: 'DELETE',
    });
  }

  async exportTaskToExcel(taskId) {
    const url = `${this.baseURL}/export/prediction/${taskId}/excel`;
    window.open(url, '_blank');
  }

  // 报表生成相关API
  async generateReport(reportData) {
    return this.request('/reports/generate', {
      method: 'POST',
      body: JSON.stringify(reportData),
    });
  }

  async getReports(params = {}) {
    const queryString = new URLSearchParams(params).toString();
    return this.request(`/reports?${queryString}`);
  }

  async downloadReport(filename) {
    const url = `${this.baseURL}/reports/download/${filename}`;
    window.open(url, '_blank');
  }

  // 行业数据相关API
  async startCrawlTask(crawlData) {
    return this.request('/industry/crawl', {
      method: 'POST',
      body: JSON.stringify(crawlData),
    });
  }

  async getIndustryData(params = {}) {
    const queryString = new URLSearchParams(params).toString();
    return this.request(`/industry/data?${queryString}`);
  }

  async getCrawlTasks(params = {}) {
    const queryString = new URLSearchParams(params).toString();
    return this.request(`/industry/crawl/tasks?${queryString}`);
  }

  // 获取四个板块的数据
  async getSectorsData() {
    return this.request('/industry/sectors/data');
  }

  // 获取Metaso查询数据
  async getMetasoQueryData(queryId) {
    return this.request(`/industry/metaso/data/${queryId}`);
  }

  // 获取Metaso查询状态
  async getMetasoQueryStatus(taskId) {
    return this.request(`/industry/metaso/query/${taskId}`);
  }

  // 获取所有Metaso查询记录
  async getAllMetasoQueries(limit = 50) {
    return this.request(`/industry/metaso/queries?limit=${limit}`);
  }

  // 报表相关API
  async getReportData(taskId) {
    return this.request(`/prediction/report/${taskId}`);
  }

  // LLM行业分析
  async getIndustryAnalysis(prompt, taskId = null) {
    return this.post('/llm/industry-analysis', { prompt, task_id: taskId });
  }
}

export default new ApiService();

